package com.example.autopia.view.Activities

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.example.autopia.R
import com.example.autopia.databinding.ActivityCommentsBinding
import com.example.autopia.model.Item.Comment
import com.example.autopia.model.Item.News
import com.example.autopia.model.Repositories.NewsRepository
import com.example.autopia.model.Repositories.TestRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.utilities.KEY_BD_NEWS
import com.example.autopia.utilities.TimeManager
import com.example.autopia.view.Adapters.CommentsAdapter
import com.example.autopia.view.Listeners.ChannelsListener
import com.example.autopia.view.Listeners.CommentListener
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.ktx.Firebase

class CommentsActivity : AppCompatActivity() {

    private lateinit var binding: ActivityCommentsBinding
    private val newsRepository = NewsRepository()
    private val userRepository = UsersRepository()
    private val timeManager = TimeManager()
    private lateinit var adapter: CommentsAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCommentsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val newsId = intent.getStringExtra("newsId")
        val firebaseAuth = Firebase.auth

        adapter = CommentsAdapter()
        binding.recyclerView.adapter = adapter
        binding.sendComment.setOnClickListener {
            if (binding.input.text.toString().isNotEmpty() && newsId != null) {
                val user = userRepository.getUserById(firebaseAuth.currentUser?.uid ?: "")
                user.observe(this) { user ->
                    val com = Comment(
                        "1",
                        user.name,
                        user.photo,
                        binding.input.text.toString(),
                        timeManager.getCurrentUnixTime(),
                        user.id
                    )
                    newsRepository.addComment(newsId, com)
                    binding.input.text.clear()
                }
            } else {
                if (binding.input.text.toString().isNotEmpty()) {
                    Toast.makeText(this@CommentsActivity, "Введите коментарий", Toast.LENGTH_SHORT)
                        .show()
                }
                if (newsId != null) {
                    Toast.makeText(this@CommentsActivity, "Ошибка", Toast.LENGTH_SHORT).show()
                }
            }
        }

        if (newsId != null) {
            val databaseReference =
                FirebaseDatabase.getInstance().getReference(KEY_BD_NEWS).child(newsId)

            val valueEventListener = object : ValueEventListener {
                override fun onDataChange(dataSnapshot: DataSnapshot) {
                    // Этот метод вызывается каждый раз, когда данные в базе данных изменяются
                    val commentsList = ArrayList<Comment>()
                    for (comments in dataSnapshot.child("comments").children) {
                        val id = comments.child("id").value.toString()
                        val time = comments.child("time").value.toString().toInt()
                        val text = comments.child("text").value.toString()
                        val username = comments.child("username").value.toString()
                        val userphoto = comments.child("userphoto").value.toString()
                        val userid = comments.child("userid").value.toString()
                        val com =Comment(id,username,userphoto,text,time,userid)
                        commentsList.add(com)
                    }
                    adapter.setData(commentsList)
                }

                override fun onCancelled(databaseError: DatabaseError) {
                    Toast.makeText(
                        this@CommentsActivity,
                        "Ошибка обновления списка",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            databaseReference.addValueEventListener(valueEventListener)
        }

        binding.btBack.setOnClickListener {
            finish()
        }
        adapter.setData(TestRepository.getCommentList())

        if (newsId != null) {
            setData(newsId)
            adapter.attachListener(object : CommentListener {
                override fun onCommentClick(comment:Comment) {
                     newsRepository.removeComment(newsId = newsId, commentId = comment.id)

                }
            })

        }

        adapter.attachListenerChannels(object : ChannelsListener {
            override fun onChannelClick(userid:String) {
                Toast.makeText(this@CommentsActivity, "В канал", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun setData(newsId: String) {
        val news = newsRepository.getNewsById(newsId ?: "")
        news.observe(this) {
            if (it.comments != null) {
                adapter.setData(it.comments)
                binding.recyclerView.visibility = View.VISIBLE
                binding.loading.visibility = View.GONE
            }
        }
    }
}